package com.rankeiot.platform.util;

import jakarta.servlet.http.HttpServletRequest;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


public class LockStatusBL {
	private static Map<String, ConcurrentHashMap<String,Boolean>> statusMap = new ConcurrentHashMap<>();
	/**
	 * 在同一个type和status下,同一时间只运行同一个runnable运行
	 * @param type
	 * @param status
	 * @param runnable
	 * @return 如果已锁，返回true，否则返回false并运行runnable
	 */
	public static boolean lockStatus(String type,String status,Runnable runnable){
		ConcurrentHashMap<String,Boolean> _status;
		if(statusMap.containsKey(type)){
			_status=statusMap.get(type);
		}else{
			_status=new ConcurrentHashMap();
			statusMap.put(type, _status);
		}
		if(_status.containsKey(status)){
			return true;
		}
		_status.put(status, true);
		try{
			runnable.run();
		}finally{
			_status.remove(status);
		}
		return false;
	}
	/**
	 * 这个状态是否已锁住
	 * @param type
	 * @param status
	 * @return
	 */
	public static boolean hasLock(String type,String status){
		if(statusMap.containsKey(type)){
			ConcurrentHashMap<String,Boolean> _status=statusMap.get(type);
			return _status.containsKey(status);
		}else{
			return false;
		}
	}
	/**
	 * 间隔5秒以上
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static boolean interval_over_5s(HttpServletRequest request){
		if (request.getSession().getAttribute("User_Submit_Limit") == null ){
			return true;
		}		
		Queue<Long> queue = (Queue<Long>) request.getSession().getAttribute("User_Submit_Limit");
		System.out.println("queue.getLastQueue():"+queue.getLastQueue());
		System.out.println("System.currentTimeMillis() / 1000:"+System.currentTimeMillis() / 1000);
		System.out.println("3:"+(System.currentTimeMillis() / 1000 - queue.getLastQueue()));
		if ((System.currentTimeMillis() / 1000 - queue.getLastQueue()) >= 5){
			return true;
		}
		return false;
	}
	/**
	 * 一分钟超过10次
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static boolean  more_than_10_times_a_minute(HttpServletRequest request){
		if (request.getSession().getAttribute("User_Submit_Limit") == null ){
			return false;
		}		
		Queue<Long> queue = (Queue<Long>) request.getSession().getAttribute("User_Submit_Limit");
		if ( queue.isFull() && (System.currentTimeMillis() / 1000 - queue.getFirstQueue()) < 60){
			return true;
		}
		return false;
	}
	/**
	 * 增加提交次数记录
	 */
	@SuppressWarnings("unchecked")
	public static void addQueue(HttpServletRequest request){
		Queue<Long> queue = new Queue<Long>(11);
		if (request.getSession().getAttribute("User_Submit_Limit") != null ){
			queue = (Queue<Long>) request.getSession().getAttribute("User_Submit_Limit");
		}
		queue.enQueue(System.currentTimeMillis() / 1000);
		request.getSession().setAttribute("User_Submit_Limit", queue);
	}

}
